<?php
declare(strict_types=1);

namespace App\Common\Extend\Guard;

use Hyperf\Context\ApplicationContext;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Zms\Exception\{
    DataException, AppException
};
use function Hyperf\Config\config;

/**
 * 登录组件
 */
class UserAuth
{

    /**
     * @param string $guardName
     * @return Guard
     * @throws AppException
     * @throws DataException
     */
    public static function guard(string $guardName): Guard
    {
        try {
            $className = implode('\\', [Guard::class, $guardName]);
            if (ApplicationContext::getContainer()->has($className)) {
                return ApplicationContext::getContainer()->get($className);
            }
            $conf = config("guard");
            if (isset($conf[$guardName]) && $conf[$guardName] instanceof \App\Common\Extend\Guard\Config) {
                $guard = new Guard($conf[$guardName]);
                ApplicationContext::getContainer()->set($className, $guard);
                return $guard;
            }
            throw new DataException("授权模块配置错误！");
        } catch (NotFoundExceptionInterface|ContainerExceptionInterface) {
            throw new AppException("授权模块配置错误。");
        }
    }
}